package net.wofly.common.pay.alipay.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import net.wofly.common.pay.alipay.config.AliPayConfig;
import net.wofly.common.pay.alipay.config.AlipayConfigDev;
import net.wofly.common.pay.util.ClientType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Service
public class AliPayService {
    
    Logger logger = LoggerFactory.getLogger(AliPayService.class);
    
    @Autowired
    AliPayConfig aliPayConfig;
    
    public String pay(
            Integer clientType, String orderNo, String totalAmount, String orderName,
            String orderDesc) throws IOException, AlipayApiException {
        if (ClientType.PC端.getValue() == clientType.intValue()) {
            return payPc(orderNo, totalAmount, orderName, orderDesc);
        }
        if (ClientType.移动端_H5.getValue() == clientType.intValue()) {
            return payH5(orderNo, totalAmount, orderName, orderDesc);
        }
        return null;
    }
    
    private String payPc(
            String orderNo, String totalAmount, String orderName,
            String orderDesc) throws IOException, AlipayApiException {
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        AlipayClient alipayClient = null;
        if (aliPayConfig.getPayEnv().equals("dev")) {
            //获得初始化的AlipayClient
            alipayClient = new DefaultAlipayClient(AlipayConfigDev.gatewayUrl, AlipayConfigDev.app_id,
                    AlipayConfigDev.merchant_private_key, "json", AlipayConfigDev.charset,
                    AlipayConfigDev.alipay_public_key,
                    AlipayConfigDev.sign_type);
            alipayRequest.setReturnUrl(AlipayConfigDev.return_url_pc);
            alipayRequest.setNotifyUrl(AlipayConfigDev.notify_url);
        } else {
            //获得初始化的AlipayClient
            alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getApp_id(),
                    aliPayConfig.getMerchant_private_key(), "json", AlipayConfigDev.charset,
                    aliPayConfig.getAlipay_public_key(),
                    AlipayConfigDev.sign_type);
            alipayRequest.setReturnUrl(aliPayConfig.getReturn_url_pc());
            alipayRequest.setNotifyUrl(aliPayConfig.getNotify_url());
        }
        
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderNo.getBytes("ISO-8859-1"), "UTF-8");
        //付款金额，必填
        String total_amount = new String(totalAmount.getBytes("ISO-8859-1"), "UTF-8");
        //订单名称，必填
        String subject = new String(orderName);
        //商品描述，可空
        String body = new String(orderDesc.getBytes("ISO-8859-1"), "UTF-8");
        
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        
        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        
        logger.info(">>> BizContent:"+ alipayRequest.getBizContent());
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        
        return result;
        //输出
        //response.getWriter().write(result);
    }
    
    private String payH5(
            String orderNo, String totalAmount, String orderName,
            String orderDesc) throws UnsupportedEncodingException {
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderNo.getBytes("ISO-8859-1"), "UTF-8");
        // 订单名称，必填
        String subject = new String(orderName.getBytes("ISO-8859-1"), "UTF-8");
        System.out.println(subject);
        // 付款金额，必填
        String total_amount = new String(totalAmount.getBytes("ISO-8859-1"), "UTF-8");
        // 商品描述，可空
        String body = new String(orderDesc.getBytes("ISO-8859-1"), "UTF-8");
        // 超时时间 可空
        String timeout_express = "2m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getApp_id(),
                aliPayConfig.getMerchant_private_key(), "json", AlipayConfigDev.charset,
                aliPayConfig.getAlipay_public_key(),
                AlipayConfigDev.sign_type);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
        
        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(aliPayConfig.getNotify_url());
        // 设置同步地址
        alipay_request.setReturnUrl(aliPayConfig.getReturn_url_h5());
        
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            /*response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            //直接将完整的表单html输出到页面
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();*/
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        logger.info(">>> "+form);
        return form;
    }
}
